//
//  ViewController.swift
//  XNImageGradation
//
//  Created by xiaoxun on 2024/9/24.
//

import UIKit

class ViewController: UIViewController {
    
    override func viewDidLoad() {
        super.viewDidLoad()
        // Do any additional setup after loading the view.
        
        self.view.backgroundColor = .red
        let imageView: UIImageView = UIImageView(frame: self.view.bounds)
        self.view.addSubview(imageView)
        imageView.contentMode = .scaleAspectFill
        let ss: UIImage = UIImage(named: "8")!
        if let ii: UIImage = self.createOpaqueToTransparentImage(size: ss.size) {
            imageView.image = self.blendImages(image: ss, gradientImage: ii)
        }
        
    }
    
    
    // 创建一个函数，用于生成顶部不透明、底部透明的图像
    func createOpaqueToTransparentImage(size: CGSize) -> UIImage? {
        UIGraphicsBeginImageContextWithOptions(size, false, 0.0)
        // 获取绘图上下文
        guard let context = UIGraphicsGetCurrentContext() else { return nil }
        // 定义渐变的起始和结束颜色
        let topColor = UIColor.black
        let bottomColor = UIColor.clear
        // 创建渐变色
        let colors = [topColor.cgColor, bottomColor.cgColor] as CFArray
        let locations: [CGFloat] = [0.0, 1.0]
        // 创建渐变
        if let gradient = CGGradient(colorsSpace: nil, colors: colors, locations: locations) {
            // 绘制渐变
            context.drawLinearGradient(gradient, start: CGPoint(x: 0, y: 0), end: CGPoint(x: 0, y: size.height), options: [])
            // 从绘图上下文中创建图像
            if let gradientImage = UIGraphicsGetImageFromCurrentImageContext() {
                UIGraphicsEndImageContext()
                return gradientImage
            }
        }
        UIGraphicsEndImageContext()
        return nil
    }
    
    // 创建一个函数，用于将两个图像融合成一个顶部不透明、底部透明的图像
    func blendImages(image: UIImage, gradientImage: UIImage) -> UIImage? {
        UIGraphicsBeginImageContextWithOptions(image.size, false, 0.0)
        // 绘制原始图像
        image.draw(in: CGRect(x: 0, y: 0, width: image.size.width, height: image.size.height))
        // 绘制渐变图像
        gradientImage.draw(in: CGRect(x: 0, y: 0, width: gradientImage.size.width, height: gradientImage.size.height), blendMode: .destinationIn, alpha: 1.0)
        // 从绘图上下文中创建融合后的图像
        let blendedImage = UIGraphicsGetImageFromCurrentImageContext()
        UIGraphicsEndImageContext()
        return blendedImage
    }
    
}
